package com.cqhz.quwan.ui.base

import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.os.Looper
import android.os.Message
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import com.alipay.sdk.app.AuthTask
import com.alipay.sdk.app.PayTask
import com.cqhz.quwan.R
import com.cqhz.quwan.model.AlipayAuthData
import com.cqhz.quwan.model.LayoutInit
import com.cqhz.quwan.mvp.IBasicView
import com.cqhz.quwan.mvp.mine.AlipayContract
import com.cqhz.quwan.service.WechatPayContract
import com.cqhz.quwan.util.*
import com.gyf.barlibrary.ImmersionBar
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import me.militch.quickcore.util.ApiException


abstract class AbsActivity : AppCompatActivity(), IBasicView, AlipayContract.View, WechatPayContract.View {
    private lateinit var loadingToast: LoadingToast
    private lateinit var aliPayHandler: AliPayHandler
    private var mInputMethodManager: InputMethodManager? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        loadingToast = LoadingToast.create(this)
        aliPayHandler = AliPayHandler(this)
        setContentView(layout())
        beforeInitView()
        //初始化沉浸式
        if (isImmersionBarEnabled()) {
            initImmersionBar()
        }
        initView()
    }

    override fun onStop() {
        super.onStop()
        hintLoading()
    }

    abstract fun layout(): Int
    open fun beforeInitView() {}
    override fun alipayAuthCallBack(authData: AlipayAuthData) {

    }

    override fun alipayAuthFail(authResult: AuthResult) {

    }

    override fun alipayFail(payResult: PayResult) {

    }

    override fun alipayCallBack() {

    }

    abstract fun initView()
    override fun showToast(toast: String) {
        Toast.makeText(this, toast, Toast.LENGTH_SHORT).show()
    }


    private fun createLoadingDialog(): AlertDialog {
        return AlertDialog.Builder(this)
                .setCancelable(false)
                .setView(R.layout.layout_loading)
                .setMessage("").create()
    }

    override fun showRequestError(e: ApiException) {
        hintLoading()
        if (e.cause != null) {
            val t = e.cause
            showToast("加载失败，请重试")
            return
        }
        showToast(e.message ?: "")
    }

    override fun toIntent(clazz: Class<*>) {
        startActivity(Intent(this, clazz))
    }

    override fun closePage() {
        finish()
    }

    override fun showLoading() {
        runOnUiThread {
            lockWindow(true)
//        oldShowToastTime = System.currentTimeMillis()
            showLoading(getString(R.string.label_loading))
        }

    }

    override fun showLoading(text: String) {
        runOnUiThread {
            lockWindow(true)
            loadingToast.show(text)
        }


    }

    override fun hintLoading() {
        runOnUiThread {
            lockWindow(false)
            if (loadingToast.showing()) {
                loadingToast.hint()
            }
        }
    }

    override fun context(): Context {
        return this
    }

    override fun toIntent(intent: Intent) {
        startActivity(intent)
    }

    override fun callAlipay(arg: String) {
        val t = Thread({
            Looper.prepare()
            val payTask = PayTask(this)
            val result = payTask.payV2(arg, true)
            val msg = Message()
            msg.what = AliPayHandler.ALIPAY_PAY_FLAG
            msg.obj = result
            aliPayHandler.handleMessage(msg)
            Looper.loop()
        })
        t.start()
    }

    override fun callAlipayAuth(arg: String) {
        val t = Thread({
            Looper.prepare()
            val at = AuthTask(this)
            val result = at.authV2(arg, true)
            val msg = Message()
            msg.what = AliPayHandler.ALIPAY_AUTH_FLAG
            msg.obj = result
            aliPayHandler.handleMessage(msg)
            Looper.loop()
        })
        t.start()
    }

    open fun initLayout(): (LayoutInit.() -> Unit)? {
        return null
    }

    override fun wechatPayCallBack(appId: String) {

    }

    override fun callWechatPay(wechatPayResp: WechatPayContract.WechatPayResp) {
        val wechatApi = WXAPIFactory.createWXAPI(this, null)
        wechatApi.registerApp(wechatPayResp.appid)
        val payReq = PayReq()
        payReq.appId = wechatPayResp.appid
        payReq.partnerId = wechatPayResp.partnerid
        payReq.prepayId = wechatPayResp.prepayid
        payReq.packageValue = wechatPayResp.packageValue
        payReq.nonceStr = wechatPayResp.noncestr
        payReq.timeStamp = wechatPayResp.timestamp
        payReq.sign = wechatPayResp.sign
        wechatApi.sendReq(payReq)
    }

    override fun onDestroy() {
        super.onDestroy()
        mInputMethodManager = null
        if (isImmersionBarEnabled()) {
            ImmersionBar.with(this).destroy()
        }
    }

    open fun initImmersionBar() {
        ImmersionBar.with(this)
                .fitsSystemWindows(true)// 使用该属性,必须指定状态栏颜色
                .statusBarColor(R.color.colorPrimary)
                .init()
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        if (isImmersionBarEnabled()) {
            ImmersionBar.with(this).init()
        }
    }

    /**
     * 是否可以使用沉浸式
     * Is immersion bar enabled boolean.
     *
     * @return the boolean
     */
    open fun isImmersionBarEnabled(): Boolean {
        return true
    }

    override fun finish() {
        super.finish()
        hideSoftKeyBoard()
    }

    open fun hideSoftKeyBoard() {
        val localView = currentFocus
        if (this.mInputMethodManager == null) {
            this.mInputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        }
        if (localView != null && this.mInputMethodManager != null) {
            this.mInputMethodManager!!.hideSoftInputFromWindow(localView.windowToken, 2)
        }
    }
}